package feeinterface.protocol.req;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.ulwx.tool.ArrayUtils;
import com.ulwx.tool.RequestUtils;
import com.ulwx.tool.StringUtils;
import com.ulwx.type.TString;

import feeinterface.dao.BaseAreaDao;
import feeinterface.dao.BaseFindAreaByIPErrorDao;
import feeinterface.dao.BaseGatewayKeywordDao;
import feeinterface.dao.BaseIPNetworkDao;
import feeinterface.dao.BaseImsiPhoneDao;
import feeinterface.dao.BasePhoneAreaCollectDao;
import feeinterface.dao.BasePhoneAreaDao;
import feeinterface.modeldb.BaseGatewayKeyword;
import feeinterface.modeldb.BaseIPNetwork;
import feeinterface.modeldb.BaseImsiPhone;
import feeinterface.modeldb.BasePhoneArea;
import feeinterface.modeldb.BasePhoneAreaCollect;
import feeinterface.protocol.utils.Constants;
import feeinterface.utils.PhoneUtils;

/**
 * 协议基类
 * 
 * @author 黄杰
 * 
 */
public abstract class Protocol {
	/**
	 * 日志
	 */
	private static Logger log = Logger.getLogger(Protocol.class);
	/**
	 * 请求注入
	 */
	protected RequestUtils request;
	
	private HttpServletRequest servletRequest;
	
	

	public HttpServletRequest getServletRequest() {
		return servletRequest;
	}

	public void setServletRequest(HttpServletRequest servletRequest) {
		this.servletRequest = servletRequest;
	}

	/**
	 * 获取请求注入
	 * 
	 * @return
	 */
	public RequestUtils getRequest() {
		return request;
	}

	public String getGateWayKey() {
		return this.getRequest().getString(Constants.PROTOCOL_REQ_GATEWAY_KEY);

	}

	public String getGateWayIP() {
		return this.getRequest().getString(Constants.PROTOCOL_REQ_GATEWAY_IP);
	}

	public String getPhoneFromGateWay() {
		return this.getRequest()
				.getString(Constants.PROTOCOL_REQ_GATEWAY_PHONE);
	}

	public boolean isFromServer() {
		try {
			if (this.getRequest().getByte("RequestFrom") == Constants.RequestFrom.SERVER) {
				return true;
			} else
				return false;
		} catch (Exception e) {
			return false;
		}
	}

	/**
	 * 设置请求注入
	 * 
	 * @param request
	 */
	public void setRequest(RequestUtils request) {
		this.request = request;
	}

	/**
	 * 协议编号
	 */
	public String Protocol;

	/**
	 * 业务逻辑处理
	 * 
	 * @return
	 * @throws Exception
	 */
	public abstract Object genBean() throws Exception;

	/**
	 * 
	 * @return 如果返回为null，表示验证通过；如果为非null，表明验证不通过
	 */
	public abstract String validate() throws Exception;

	/*
	 * 返回省份ID和城市ID 第一个：省份id 第二个：城市id
	 */
	public int[] getAreaID(String imsi, String smsCenter) {
		String ip = this.getGateWayIP();// IP
		String gateKey = this.getGateWayKey();// 关键字
		String phoneFromGateWay = this.getPhoneFromGateWay();
		Integer[] tempareaID = getAreaID("", imsi, ip, gateKey, smsCenter,
				phoneFromGateWay, new TString(""));
		if(tempareaID[0]==null) tempareaID[0]=0;
		if(tempareaID[1]==null )tempareaID[1]=0;
		int[] areaids = (int[]) ArrayUtils.toPrimitiveArray(tempareaID);
		if (this.getRequest() != null) {
			this.getRequest().setInt(Constants.PROTOCOL_REQ_PROVINCE,
					areaids[0]);
			this.getRequest().setInt(Constants.PROTOCOL_REQ_CITY, areaids[1]);
		}

		return areaids;
	}

	/*
	 * 返回省份ID和城市ID 第一个：省份id 第二个：城市id
	 */
	public int[] getAreaID(String mobile, String imsi, String smsCenter,
			TString tcarrier) {

		String ip = this.getGateWayIP();// IP
		String gateKey = this.getGateWayKey();// 关键字
		String phoneFromGateWay = this.getPhoneFromGateWay();

		Integer[] tempareaID = getAreaID(mobile, imsi, ip, gateKey, smsCenter,
				phoneFromGateWay, tcarrier);
		if(tempareaID[0]==null) tempareaID[0]=0;
		if(tempareaID[1]==null )tempareaID[1]=0;
		int[] areaids = (int[]) ArrayUtils.toPrimitiveArray(tempareaID);

		if (this.getRequest() != null) {
			this.getRequest().setInt(Constants.PROTOCOL_REQ_PROVINCE,
					areaids[0]);
			this.getRequest().setInt(Constants.PROTOCOL_REQ_CITY, areaids[1]);
		}
		return areaids;
	}

	public boolean isFromWap() {
		return this.getRequest().getBoolean(
				Constants.PROTOCOL_REQ_GATEWAY_IS_CMWAP);
	}

	/*
	 * 返回省份ID和城市ID 第一个：省份id 第二个：城市id
	 */
	protected Integer[] getAreaID(String mobile, String imsi, String ip,
			String gateKey, String smsCenter, String phoneFromGateWay,
			TString carrier) {

		if (carrier == null)
			carrier = new TString("");

		Integer[] areaIDs = { Constants.Area.UNKNOWN_PROVINCEID,
				Constants.Area.UNKNOWN_CITYID };
		try {

			// 修改者孙超进,2011-03-29，如果从网关得到手机号码，首先使用网关的手机号码判断地区
			if (StringUtils.hasText(mobile)
					|| StringUtils.hasText(phoneFromGateWay)) {
				phoneFromGateWay = StringUtils.trim(phoneFromGateWay);
				mobile = StringUtils.trim(mobile);
				String newPhone = "";
				if (StringUtils.hasText(mobile)) {
					newPhone = mobile;
				} else if (StringUtils.hasText(phoneFromGateWay)) {
					newPhone = phoneFromGateWay;
				}
				newPhone = PhoneUtils.getAdjustedPhone(newPhone);
				// String car = PhoneUtils.getCarrierFromPhone(newPhone);
				// if (!car.equals("未知")) {}

				// 再次确认是否为手机号码
				// carrier.setValue(StringUtils.trim(car));
				// 根据手机号码找地区
				BasePhoneArea ba = BasePhoneAreaDao.getByPhone(newPhone
						.substring(0, 7));
				carrier.setValue("未知");
				if (ba != null) {
					carrier.setValue(StringUtils.trim(ba.getCarrier()));
					areaIDs[0] = ba.getProvinceID();
					areaIDs[1] = ba.getCityID();
					carrier.setValue(ba.getCarrier());
					return areaIDs;

				} else {// 收集
					BasePhoneAreaCollect bpa = new BasePhoneAreaCollect();
					bpa.setPhone7(newPhone.substring(0, 7));
					BasePhoneAreaCollectDao.insert(bpa);

					String car = PhoneUtils.getCarrierFromPhone(newPhone);
					carrier.setValue(StringUtils.trim(car));
				}

			}

			if (imsi != null && imsi.length() > 3
					&& imsi.substring(0, 3).equals("460")) {
				// 根据IMSI找地区
				BaseImsiPhone bip = BaseImsiPhoneDao.getPhoneBy(imsi);
				if (bip != null) {
					String phone = bip.getPhone();

					BasePhoneArea ba = BasePhoneAreaDao.getByPhone(phone
							.substring(0, 7));
					if (ba != null) {
						carrier.setValue(StringUtils.trim(ba.getCarrier()));
						if (ba.getProvinceID() != null)
							areaIDs[0] = ba.getProvinceID();
						if (ba.getCityID() != null)
							areaIDs[1] = ba.getCityID();
						return areaIDs;

					} else {
						// 收集
						BasePhoneAreaCollect bpa = new BasePhoneAreaCollect();
						bpa.setPhone7(phone.substring(0, 7));
						BasePhoneAreaCollectDao.insert(bpa);

						String car = PhoneUtils.getCarrierFromPhone(phone);
						carrier.setValue(StringUtils.trim(car));
						areaIDs[0] = bip.getProvinceID();
						areaIDs[1] = bip.getCityID();
						return areaIDs;
					}

				}
			}

			// 根据短信中心号码找地区
			if (StringUtils.hasText(smsCenter)) {

				if (smsCenter.length() > 11) {
					smsCenter = smsCenter.substring(smsCenter.length() - 11);
				}
				String newSmsCenter = PhoneUtils.getAdjustedPhone(smsCenter);
				String phone7 = newSmsCenter.substring(0, 7);
				BasePhoneArea ba = BasePhoneAreaDao.getByPhone(phone7);
				// BaseArea ba = BaseAreaDao.getByAreaCode(areaCode);
				// 优化：截取前面七位手机号段，在BasePhoneArea找
				if (ba != null) {
					carrier.setValue(StringUtils.trim(ba.getCarrier()));
					int[] areaids = new int[] { ba.getProvinceID(),
							ba.getCityID() };
					if (areaids[0] != -1 && areaids[1] != -1) {
						areaIDs[0] = areaids[0];
						areaIDs[1] = areaids[1];
						return areaIDs;
					}
				} else {
					// 收集
					BasePhoneAreaCollect bpa = new BasePhoneAreaCollect();
					bpa.setPhone7(newSmsCenter.substring(0, 7));
					BasePhoneAreaCollectDao.insert(bpa);

					String car = PhoneUtils.getCarrierFromPhone(newSmsCenter);
					carrier.setValue(StringUtils.trim(car));
				}

			}

			// 根据ip找地区
			if (StringUtils.hasText(ip)) {
				BaseIPNetwork bit = BaseIPNetworkDao.getByIP(ip);

				if (bit != null) {
					carrier.setValue(StringUtils.trim(bit.getCarrier()));
					// int[] areaids = BaseAreaDao.getProvinceAndCityID(bit
					// .getCityID());
					areaIDs[0] = bit.getProvinceID();
					areaIDs[1] = bit.getCityID();
					return areaIDs;
				} else {
					BaseFindAreaByIPErrorDao.insert(ip);
				}

			}

			// 根据关键字找地区
			if (StringUtils.hasText(gateKey)) {
				BaseGatewayKeyword ck = BaseGatewayKeywordDao.getByKey(gateKey);

				if (ck != null) {
					carrier.setValue(StringUtils.trim(ck.getCarrier()));
					int[] areaids = BaseAreaDao.getProvinceAndCityID(ck
							.getProvinceID());
					if (areaids[0] != -1 && areaids[1] != -1) {
						areaIDs[0] = areaids[0];
						areaIDs[1] = areaids[1];
						return areaIDs;
					}
				}

			}

		} catch (Exception e) {
			// e.printStackTrace();
			log.error("", e);
		}

		return areaIDs;

	}

}
